import router,{constantRoutes} from '@/router/routers.js'
import  roleApi from '@/api/system/menu.js'
//import * as Auth from '@/libs/wechat';
import {formatRoutes} from '@/utils/parsing'
import { getAsyncRoutes} from '@/utils/asyncRouter.js'
import store from '@/store'
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.child) {
      tmp.child = filterAsyncRoutes(tmp.child, roles)
    }
    res.push(tmp)
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  topbarRouters: [],
  sidebarRouters: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
	  
    state.addRoutes = routes
    // state.routes = constantRoutes.concat(routes)
    state.routes = routes
  },
  SET_TOPBAR_ROUTES: (state, routes) => {
    state.topbarRouters = routes
  },
  SET_SIDEBAR_ROUTERS: (state, routes) => {
    state.sidebarRouters = routes
  },
}

const actions = {
  generateRoutes({ commit }, roleid) {
    return new Promise(async resolve => {
      let accessedRoutes = []
      let menus= []
      // const { rules } = await roleApi.getRoleById(roleid)
      let menusAll = await roleApi.list()
      menusAll = formatRoutes(menusAll.menuInfo)
	  localStorage.setItem("menus",JSON.stringify(menusAll))
      //!Auth.isPhone() ? menus = menusAll.filter(item => item.url !== '/javaMobile') : menus = menusAll.filter(item => item.url === '/javaMobile')
     // const _routerResult = comRouter(menusAll)
      accessedRoutes = filterAsyncRoutes(constantRoutes)
      // todo 这里控制是否过滤路由，经测试有些菜单不能予以设置，比如系统设置等等
      this.state.settings.showSettings = false
      commit('SET_ROUTES', menus)
      commit('SET_TOPBAR_ROUTES', menus)
      if(this.state.settings.topNav){
        commit('SET_SIDEBAR_ROUTERS', state.sidebarRouters.length ? state.sidebarRouters : menus[0].child)
      }else{
        commit('SET_SIDEBAR_ROUTERS', menus)
      }
	  
      // resolve(menus)
      // commit('SET_ROUTES', accessedRoutes)
      resolve(menusAll)

      // commit('SET_ROUTES', asyncRoutes)
      // resolve(asyncRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
